package term

import (
	"context"
	// "fmt"
	"strconv"

	"mall/common/utils/pointy"
	"mall/service/attachment/rpc/attachmentclient"
	"mall/service/backend/api/internal/logic/media/util"
	"mall/service/backend/api/internal/logic/utils"
	"mall/service/backend/api/internal/logic/utils/parse"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/i18n"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetTermListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetTermListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetTermListLogic {
	return &GetTermListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetTermListLogic) GetTermList(req *types.MediaTermListReq) (resp *types.MediaTermListResp, err error) {
	// logrus.Info(fmt.Sprintf("TermListReq: %+v", req))

	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	orderBys := util.ParseSorter(req.Sorter)
	filterBys := util.ParseFilter(req.Filter)

	var ids *string
	if req.Id != nil && *req.Id > 0 {
		ids = pointy.GetPointer(strconv.FormatInt(int64(*req.Id), 10))
	}

	data, err := l.svcCtx.AttachmentRpc.BackendGetTermList(l.ctx, &attachmentclient.TermListReq{
		Page:      page,
		PageSize:  pageSize,
		Ids:       ids,
		Name:      req.Name,
		Slug:      req.Slug,
		Taxonomy:  req.Taxonomy,
		ParentId:  req.ParentId,
		GroupId:   req.GroupId,
		Status:    req.Status,
		StartTime: req.StartTime,
		EndTime:   req.EndTime,
		OrderBy:   orderBys,
		FilterBy:  filterBys,
	})
	if err != nil {
		return
	}

	resp = &types.MediaTermListResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: types.MediaTermListInfo{
			BaseListInfo: types.BaseListInfo{
				Current:  page,
				PageSize: pageSize,
				Total:    data.GetTotal(),
			},
		},
	}
	for _, v := range data.List {
		option := utils.GetOptionByStatus(v.Status)
		resp.Data.List = append(resp.Data.List, &types.MediaTermInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:         v.Id,
				CreatedAt:  v.CreatedAt,
				UpdatedAt:  v.UpdatedAt,
				DeletedAt:  v.DeletedAt,
				CanAccept:  option.CanAccept,
				CanReject:  option.CanReject,
				CanRemove:  option.CanRemove,
				CanRestore: option.CanRestore,
			},
			Name:     v.Name,
			Slug:     v.Slug,
			Taxonomy: v.Taxonomy,
			ParentId: v.ParentId,
			GroupId:  v.GroupId,
			Desc:     v.Desc,
			Sort:     v.Sort,
			Status:   v.Status,
			Count:    v.Count,
		})
	}

	return resp, nil
}
